<?php


namespace App\Http\Controllers\Api\Driver;


use App\Exports\CarDriverExport;
use App\Exports\CarExport;
use App\Imports\CarDriverImport;
use App\Http\Controllers\Controller;
use App\Http\Requests\CarRequest;
use App\Http\Requests\StateRequest;
use App\Imports\DriverImport;
use App\Imports\DriverOtherImport;
use App\Repositories\CarRepository;
use App\Repositories\DriverRepository;
use App\Services\CarService;
use App\Transforms\CarTransformer;
use App\Transforms\DriverTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use function GuzzleHttp\Psr7\str;


class CarController extends Controller
{

    /**
     * 车辆分页列表
     * @param Request $request
     * @param CarRepository $repository
     * @return CarController|JsonResponse
     * @Author 姿势就是力量
     */
    public function getPageList(Request $request, CarRepository $repository)
    {
        $companyId = (int)$request->get('company_id', ''); //公司id
        $number = (string)$request->get('number', '');  //车牌号
        $type = (string)$request->get('type', '');   //业务类型
        $status = (string)$request->get('status', '');  //状态
        $brand = (int)$request->get('brand', ''); //车辆品牌
        $real_name = (string)$request->get('real_name', '');  //所属司机
        $restriction = (int)$request->get('restriction', ''); //限行
        $date =(string)$request->get('created_at','');      //时间选择
        $colour=(string)$request->get('colour','');          //车辆颜色
        $owner=(string)$request->get('owner','');   //所属公司/个人
        $pageSize = (int)$request->get('page_size', 10);
        $condition = [];
        $type ? $condition['type'] = $type : false;
        $status ? $condition['status'] = $status : false;
        $list = $repository->getPageList($condition, $companyId,$brand, $restriction,$number,$real_name, $date,$colour,$owner,$pageSize);
        $list['data'] = (new CarTransformer())->transformList($list['data']);

        return $this->sendJson($list);
    }


    /**
     * 车辆详情
     * @param Request $request
     * @param CarRepository $repository
     * @return CarController|JsonResponse
     * @Author 姿势就是力量
     */
    public function getFirst(Request $request, CarRepository $repository)
    {
        $carId = (int)$request->get('car_id', '');
        $car = $repository->getFirst($carId);

        $car = (new CarTransformer())->transform($car);
        return $this->sendJson($car);
    }


    /**
     * 保存车辆信息
     * @param CarRequest $request
     * @param CarService $service
     * @return CarController|JsonResponse
     * @Author 姿势就是力量
     */
    public function save(CarRequest $request, CarService $service)
    {
        $data = $request->post();
        $res = $service->saveData($data);
        if (!$res) return $this->sendError($service->getError());

        return $this->sendSuccess('保存成功');
    }


    /**
     * 修改状态
     * @param StateRequest $request
     * @param CarRepository $repository
     * @return CarController|JsonResponse
     * @Author 姿势就是力量
     */
    public function saveState(StateRequest $request, CarRepository $repository)
    {
        $data = $request->only(['id', 'status']);
        $car = $repository->saveData($data);
        if (!$car) return $this->sendError('保存失败');

        return $this->sendSuccess('保存成功');
    }

    /**
     * 导入司机
     * @param StateRequest $request
     * @param CarRepository $repository
     * @return CarController|JsonResponse
     * @Author 姿势就是力量
     */
    public function driver(Request $request)
    {
        //获取excel文件
        $data = Excel::import(new CarDriverImport(), $request->file('file'));
        return $this->sendSuccess('导入成功');
    }

    /**
     * 代驾司机导入
     */
    public function drivers(Request $request)
    {
        $data = Excel::import(new DriverOtherImport(), $request->file('file'));
        return $this->sendSuccess('导入成功');
    }

    /**
     * 导出司机
     * @param StateRequest $request
     * @param CarRepository $repository
     * @Author 姿势就是力量
     */

    public function carExcel(Request $request,DriverRepository $repository)
    {
        $user_id = (int)$request->get('id', '5');   //用户id
        $real_name = (string)$request->get('real_name', '');//司机姓名
        $real_phone = (int)$request->get('phone', '');//司机手机号
        $identity = (string)$request->get('identity', '');    //身份证
        $companyId = (int)$request->get('company_id', '');   //公司id
        $status = (string)$request->get('status', '');       //状态
        $number = (string)$request->get('number', '');       //车牌号
        $province = (int)$request->get('province', '');   //接单省id
        $city = (int)$request->get('city', '');   //接单市id
        $date =(string)$request->get('created_at','');      //时间选择
        $row = [
            [
                "id" => 'ID',
                "real_name" => '司机姓名',
                "phone" => '司机手机号',
                "name" => '管理公司',
                "number" => '绑定车辆号牌',
                "host" => '主司机',
                "s_name" => '车辆业务类型',
                "b_name" => '车辆品牌',
            ]
        ];
        $list = DB::table('drivers')
            ->leftjoin('driver_car', 'drivers.id', '=', 'driver_car.driver_id')
            ->leftJoin('car', 'driver_car.car_id', '=', 'Car.id')
            ->leftJoin('company', 'car.company_id', '=', 'company.id')
            ->leftJoin('car_brand as b', 'car.brand_id', '=', 'b.id')
            ->leftJoin('service_type as s', 'car.type', '=', 's.id')
            ->when($real_name, function ($query) use ($real_name) {
                $query->where('drivers.real_name', 'like', '%' . $real_name . '%');
            })//查询司机姓名
            ->when($real_phone, function ($query) use ($real_phone) {
                $query->where('drivers.phone', 'like', '%' . $real_phone . '%');
            })//查询司机手机号
            ->when($identity, function ($query) use ($identity) {
                $query->where('drivers.identity', 'like', '%' . $identity . '%');
            })//查询身份证
            ->when($companyId, function ($query) use ($companyId) {
                $query->where('car.company_id', 'like', '%' . $companyId . '%');
            })//查询公司id
            ->when($status, function ($query) use ($status) {
                $query->where('drivers.status', 'like','%'.$status.'%');
            }) //状态
            ->when($number, function ($query) use ($number) {
                $query->where('car.number', 'like','%'.$number.'%');
            }) //车牌号
            ->when($province, function ($query) use ($province) {
                $query->where('drivers.province','like','%'.$province.'%');
            }) //车牌号
            ->when($city, function ($query) use ($city) {
                $query->where('drivers.city','like','%'.$city.'%');
            }) //省id
            ->when($date, function ($query) use ($date) {
                 if($date){
                    $list = explode(',',$date);
                    $query->whereBetween('drivers.created_at', [$list[0],$list[1]]);
                 }
            }) //时间选择
            ->select('drivers.id',  'drivers.real_name', 'drivers.phone','company.name', 'car.number','driver_car.host',  'b.name as b_name', 's.name as s_name')
          ->where('car.company_id',$user_id )
            ->orderBy('id', 'asc')
            ->get();
        $list->each(function ($item){
            $item->host = trim($item->host) == '1' ? '是' : '否';
        });
        return Excel::download(new  CarDriverExport($row, $list->toArray()), '车辆导入.xls');

    }

    public function delete()
    {


    }
}
